<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/25
 * Time: 9:48
 */

namespace app\api\controller\android\v12;


use app\api\model\Authority;

use app\api\model\OrderModel;
use app\api\model\PurchaseUsage;
use app\api\model\RoutineUsage;
use think\Cache;
use think\Controller;

use think\Request;
use think\Exception;
use app\api\validate;
use  app\api\model\Approval;
use Think\Db;


class NewMaterial extends Controller
{
    protected $model;
    protected $us;

    //库存分类查询
    const  ClassificationQuery = '/bdinvcl/query';
    //报销凭证插入
    const  u8cReimbursement = '/voucher/insertU8c';
    //报销凭证插入批量
    const  u8cBath = '/voucher/insertU8cBatch';
    //存货详细信息
    const  u8cInvcDetail = '/common/invcDetail';
    //计量单位查询
    const  u8cquery = '/measdoc/query';
    //库存余额查询
    const  u8queryForStoreId= '/atp/queryForStoreId';

    //其他店铺可用数据量
    const  u8queryForOther= '/atp/queryForOther';
    //材料库存审核通过减少
    const  u8insertU8c= '/materialout/insertU8c';
    //材料价格查询
    const  u8cGetPrice= '/common/getPrice';

    //材料借调
    const  u8outAndIn= '/othersecondment/outAndIn';
    //打卡二维码
    const  qrcode= '/qrcode/chockIn';

    //库存材料出库u8c列表
    const  U8cForList= '/materialout/insertU8cForList';
    const  U8cIncode= '/common/detailOne';

    public function _initialize()
    {
        $this->model = new Authority();

        $this->us = Authority::check(1);

    }

    /**
     * 库存分类查询
     */
    public function InventoryClassificationQuery()
    {
        if($this->us['Inventory']==1){
            r_date(null, 300,'库存盘点');
        }
        $data = ClassificationQueryMaterial(1);
        $data = json_decode($data, true);
        if ($data['status'] == 'success') {
            $list = $data['data'];
        } else {
            $list = null;
        }

        r_date($list, 200);
    }
    /**
     * 查询存货信息
     */
    public function U8cIncodeQuery()
    {
        $request = Authority::param(['invclasscode']);

        $data = U8cIncode($request['invclasscode'], $this->us['store_id']);
        $data = json_decode($data, true);

        if ($data['status'] == 'success') {
            $list = $data['data'];
        } else {
            $list = null;
        }
        r_date($list, 200);
    }

    /**
     * 库存分类查询
     */
    public function Company()
    {

        $data = Company();
        $data = json_decode($data, true);
        if ($data['status'] == 'success') {
            $list = json_decode($data['data']);
        } else {
            $list = null;
        }

        r_date($list, 200);
    }

    /**
     * 存货详细信息
     */
    public function u8cMaterialInvcDetail()
    {
        $request = Authority::param(['invclasscode']);

        $data = u8cInvcDetail($request['invclasscode'], $this->us['store_id'], 1, 200,null,1);
        $data = json_decode($data, true);

        if ($data['status'] == 'success') {
            $list = $data['data'];
        } else {
            $list = null;
        }

        r_date($list, 200);
    }

    /*
     * 材料库存增加
     */
    public function u8cMaterialCollectAdd(Approval $approval)
    {
        $data = Request::instance()->post();

        db()->startTrans();
        try {

            $id = db('routine_usage')->insertGetId(['store_id' => $this->us['store_id'], 'stock_name' => '材料库存增加', 'user_id' => $this->us['user_id'], 'company' => '', 'status' => 0, 'voucher' => '', 'created_time' => time(), 'types' => 2, 'address' => $data['address'], 'phone' => $data['phone'], 'remake' => $data['remark'], 'name' => $data['name'],'order_id'=>$data['order_id']]);
            $jsonData = json_decode($data['jsonData'], true);
            foreach ($jsonData as $item) {
                db('routine_cart')->insertGetId(['id' => $id, 'invname' => $item['invname'], 'measname' => $item['measname'], 'invclcode' => $item['invclcode'], 'chooseNumber' => $item['chooseNumber'],'created_time'=>time(),'store_id' => $this->us['store_id']]);
            }
            $title = $this->us['username'] . '材料采购';
            db()->commit();
            $approval->Purchase($id, $title, $this->us['username'], 2);

            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }

    /*
     * 材料记录type  1库存补充2新材料申请
     */
    public function MaterialRecords(RoutineUsage $routineUsage, PurchaseUsage $purchaseUsage)
    {
        $request = Authority::param(['type', 'startTime', 'endTime']);

        if ($request['type'] == 1) {
            $rows = $routineUsage;
            if ($request['startTime'] != '' && $request['startTime'] != 0 && $request['endTime'] != '' && $request['endTime'] != 0) {

                $start = strtotime(date('Y-m-d 00:00:00', strtotime($request['startTime'])));//获取指定月份的第一天
                $end = strtotime(date('Y-m-d 23:59:59', strtotime($request['endTime']))); //获取指定月份的最后一天

                $rows->whereBetween('created_time', [$start, $end]);
            }
            $rows = $rows->where('types', 2)->where('secondment', 0)->where('user_id', $this->us['user_id'])->field('FROM_UNIXTIME(created_time,"%Y-%m-%d %H:%i") as created_time,id,status as statuss')->order('created_time desc')->select();


        } else {
            $rows = $purchaseUsage;
            if ($request['startTime'] != '' && $request['startTime'] != 0 && $request['endTime'] != '' && $request['endTime'] != 0) {
                $start = strtotime(date('Y-m-d 00:00:00', strtotime($request['startTime'])));//获取指定月份的第一天
                $end = strtotime(date('Y-m-d 23:59:59', strtotime($request['endTime']))); //获取指定月份的最后一天
                $rows->whereBetween('created_time', [$start, $end]);
            }
            $rows= $rows->where('user_id', $this->us['user_id'])->field('stock_name,FROM_UNIXTIME(created_time,"%Y-%m-%d %H:%i") as created_time,id,status as statuss')->order('created_time desc')->select();

        }

        foreach ($rows as $k => $item) {
            if ($request['type'] == 1) {
                $data=$routineUsage->routineCart()->where('id',$item['id'])->select();
                $rows[$k]['name'] = isset($data[0]['invname'])?$data[0]['invname']. '等' . count($data) . '类材料':'';
                if ($item['statuss'] == 2) {
                    $rows[$k]['status'] = 3;
                } elseif ($item['statuss'] == 0) {
                    $rows[$k]['status'] = 4;
                } elseif ($item['statuss'] == 1) {
                    $status = array_column($data, 'status');
                    if (in_array(2, $status)) {
                        $rows[$k]['status'] = 1;
                    } else {
                        $rows[$k]['status'] = 2;
                    }
                }

            } else {
                $rows[$k]['name'] = $item['stock_name'] . '等类材料';
                if ($item['statuss'] == 2) {
                    $rows[$k]['status'] = 3;
                } elseif ($item['statuss'] == 0) {
                    $rows[$k]['status'] = 4;
                } elseif ($item['statuss'] == 1) {
                    $rows[$k]['status'] = 2;
                }
            }


            unset($rows[$k]['routineCart'], $rows[$k]['statuss']);

        }
        r_date($rows, 200);
    }

    /*
     * 1材料库存增加详情2新材料记录详情
     */
    public function MaterialRecordsInfo(RoutineUsage $routineUsage, PurchaseUsage $purchaseUsage)
    {
        $request = Authority::param(['id', 'type']);
        if ($request['type'] == 2) {
            $type=5;
            $request = Authority::param(['id']);
            $rows = $purchaseUsage;
            $data = $rows->join('user', 'user.user_id=purchase_usage.user_id', 'left')->where('id', $request['id'])->field('stock_name,FROM_UNIXTIME(purchase_usage.created_time,"%Y-%m-%d %H:%i") as created_time,FROM_UNIXTIME(purchase_usage.adopt,"%Y-%m-%d %H:%i") as adopt,purchase_usage.id,purchase_usage.status as status,user.username,voucher,address,phone,remake,content,company,purchase_usage.number,purchase_usage.name,purchase_usage.address,purchase_usage.phone,purchase_usage.order_id')->find();
            $data['voucher'] = !empty($rows['voucher']) ? unserialize($rows['voucher']) : null;
            $rows = [
                "stock_name" => $data['stock_name'],
                "created_time" => $data['created_time'],
                "id" => $data['id'],
                "status" => $data['status'],
                "username" => $data['username'],
                "voucher" => $data['voucher'],
                "order_id" => $data['order_id'],
                "address" => $data['address'],
                "phone" => $data['phone'],
                "remake" => $data['remake'],
                "content" => $data['content'],
                "name" => $data['name'],
                "routine_cart" => [[
                    "adopt" => $data['adopt'],
                    "id" => $data['id'],
                    "invname" => $data['stock_name'],
                    "measname" => $data['company'],
                    "invclcode" =>0,
                    "chooseNumber" => $data['number'],
                    "order_id" => $data['order_id'],
                    "status" => $data['status'],
                    "content" => $data['content'],
                    "purchase_car" => 0,
                    "original_number" => $data['number'],

                ]],
            ];

        } else {
            $type=4;
            $rows = $routineUsage->with(['routineCart' => function ($query) {
                $query->withField('id');
            }]);
            $rows = $rows->join('user', 'user.user_id=routine_usage.user_id', 'left')->where('id', $request['id'])->field('stock_name,FROM_UNIXTIME(routine_usage.created_time,"%Y-%m-%d %H:%i") as created_time,routine_usage.id,routine_usage.status as status,user.username,voucher,address,phone,remake,content,name,routine_usage.order_id')->find();
            $rows['voucher'] = !empty($rows['voucher']) ? unserialize($rows['voucher']) : null;
            foreach ($rows['routine_cart'] as $k => $item) {
                if (empty($item['original_number'])) {
                    $item['original_number'] = $item['chooseNumber'];
                }
                if ($item['original_number']  != $item['chooseNumber'] && $item['status'] == 2) {
                    if(!empty( $item['content'])){
                        $item['content'] = '入库数量有差异;' . $item['content'];
                    }

                } elseif ($item['original_number'] != $item['chooseNumber']) {
                    $item['content'] = '入库数量有差异';
                }
//                if ($rows['status'] == 0) {
//                    $item['status'] = 0;
//                } elseif ($rows['status'] == 2) {
//                    $item['status'] = 2;
//                }
            }

            $rows['voucher'] = !empty($rows['voucher']) ? unserialize($rows['voucher']) : null;

        }
        $approval = db('approval', config('database.zong'))->join('bi_user', 'bi_user.user_id=approval.nxt_id', 'left')->where('approval.city_id', config('cityId'))->where('relation_id', $request['id'])->where('type',$type)->field('bi_user.username,FROM_UNIXTIME(approval.approved_time,"%Y-%m-%d %H:%i") as approved_time')->find();

        $rows['approvalUseraname'] = $approval['username'];
        $rows['approved_time'] = $approval['approved_time'];
        r_date($rows, 200);
    }

}